package NetworkCopy.NIO;

import java.io.FileOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class ServerNIO {
    public static void main(String[] args) throws IOException, InterruptedException {

        try (
                ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
                FileChannel outputChannel = new FileOutputStream("dataTargetNetNIO.bin").getChannel() ) {

            serverSocketChannel.socket().bind(new InetSocketAddress(7002));
            serverSocketChannel.configureBlocking(false);

            ByteBuffer buf = ByteBuffer.allocate(104857600);

            while(true){
                SocketChannel socketChannel = serverSocketChannel.accept();

                if(socketChannel != null){
                    long start = System.currentTimeMillis();
                    while (socketChannel.read(buf) >= 0) {
                        buf.flip();
                        outputChannel.write(buf);
                        buf.clear();
                    }
                    long end = System.currentTimeMillis();
                    System.out.println("Time: " + (end - start) + " ms");
                }
            }
        }
    }
}